<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>密钥模板管理 - 密钥管理服务</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- 共享响应式样式 -->
    <link href="shared_responsive.css" rel="stylesheet">
    <!-- 引入通用工具函数 -->
    <script src="../common/common.js"></script>
    <style>
        body {
            background-color: #f8fafc;
            background-image: radial-gradient(rgba(59, 130, 246, 0.05) 1px, transparent 1px);
            background-size: 20px 20px;
            background-position: 0 0, 10px 10px;
            color: #334155;
        }
        .card {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(59, 130, 246, 0.4);
            border-radius: 12px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.02);
            transition: all 0.3s ease;
        }
        .card:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.04);
        }
        .btn {
            transition: all 0.3s ease;
            border-radius: 8px;
        }
        .btn-primary {
            background-color: rgba(59, 130, 246, 0.15);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.3);
        }
        .btn-primary:hover {
            background-color: rgba(59, 130, 246, 0.25);
        }
        .btn-success {
            background-color: rgba(16, 185, 129, 0.15);
            color: #10b981;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }
        .btn-success:hover {
            background-color: rgba(16, 185, 129, 0.25);
        }
        .btn-danger {
            background-color: rgba(239, 68, 68, 0.15);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }
        .btn-danger:hover {
            background-color: rgba(239, 68, 68, 0.25);
        }
        .btn-warning {
            background-color: rgba(245, 158, 11, 0.15);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, 0.3);
        }
        .btn-warning:hover {
            background-color: rgba(245, 158, 11, 0.25);
        }
        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .table-row {
            transition: all 0.2s ease;
        }
        .table-row:hover {
            background-color: rgba(59, 130, 246, 0.05);
        }
        .search-input {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid rgba(148, 163, 184, 0.3);
            transition: all 0.3s ease;
        }
        .search-input:focus {
            outline: none;
            border-color: rgba(59, 130, 246, 0.5);
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
        }
        .modal-backdrop {
            backdrop-filter: blur(4px);
            background-color: rgba(0, 0, 0, 0.5);
        }
        .form-control {
            background-color: rgba(255, 255, 255, 0.9);
            border: 1px solid rgba(148, 163, 184, 0.3);
            transition: all 0.3s ease;
        }
        .form-control:focus {
            outline: none;
            border-color: rgba(59, 130, 246, 0.5);
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
        }
        .badge-active {
            background-color: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }
        .badge-inactive {
            background-color: rgba(156, 163, 175, 0.15);
            color: #9ca3af;
        }
        .checkbox-custom {
            width: 18px;
            height: 18px;
            accent-color: #3b82f6;
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: rgba(255, 255, 255, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
        }
        .spinner {
            border: 3px solid rgba(59, 130, 246, 0.2);
            border-top: 3px solid #3b82f6;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="p-6">
    <!-- Toast通知容器 -->
    <div id="toast-container" class="fixed top-4 right-4 z-50 flex flex-col gap-2"></div>
    <div class="container mx-auto">
        <!-- 页面标题和返回按钮 -->
        <div class="mb-6 flex items-center justify-between">
            <h1 class="text-3xl font-bold text-gray-800">密钥模板管理</h1>
            <a href="index.html" class="back-btn px-4 py-2 rounded-lg flex items-center gap-2 text-gray-600">
                <i class="fas fa-arrow-left"></i>
                <span>返回首页</span>
            </a>
        </div>

        <!-- 操作栏 -->
        <div class="card p-6 mb-6">
            <div class="flex flex-wrap justify-between items-center gap-4">
                <div class="flex flex-wrap gap-2">
                    <select class="input-field px-4 py-2" id="templateTypeFilter">
                        <option value="">所有模板类型</option>
                        <option value="SM2">SM2</option>
                        <option value="RSA">RSA</option>
                        <option value="SM4">SM4</option>
                        <option value="AES">AES</option>
                    </select>
                    <input type="text" class="input-field px-4 py-2" id="searchInput" placeholder="搜索模板...">
                </div>
                <div class="flex flex-wrap gap-2">
                    <button class="btn btn-primary px-4 py-2 rounded-lg" onclick="openAddTemplateModal()">
                        <i class="fas fa-plus"></i> 新增模板
                    </button>
                </div>
            </div>
        </div>

        <!-- 模板表格 -->
        <div class="card p-6">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-gray-200">
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">模板ID</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">模板名称</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">算法</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">默认长度</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">用途</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">状态</th>
                            <th class="text-left py-3 px-4 font-semibold text-sm text-gray-600">操作</th>
                        </tr>
                    </thead>
                    <tbody id="templatesTableBody">
                        <!-- 模板数据将通过JavaScript动态生成 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 加载中遮罩 -->
    <div id="loadingOverlay" class="loading-overlay hidden">
        <div class="spinner"></div>
    </div>

    <!-- 新增模板模态框 -->
    <div id="addTemplateModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="card p-6 w-full max-w-lg">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">新增密钥模板</h3>
                <button onclick="closeAddTemplateModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="addTemplateForm" class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">模板名称</label>
                    <input type="text" name="name" class="input-field w-full px-4 py-2" placeholder="请输入模板名称" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">算法</label>
                    <select name="algorithm" class="input-field w-full px-4 py-2" required>
                        <option value="">请选择算法</option>
                        <option value="SM2">SM2</option>
                        <option value="RSA">RSA</option>
                        <option value="SM4">SM4</option>
                        <option value="AES">AES</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">默认密钥长度</label>
                    <input type="number" name="defaultLength" class="input-field w-full px-4 py-2" min="128" max="4096" placeholder="例如: 128, 256, 1024" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">用途</label>
                    <textarea name="purpose" class="input-field w-full px-4 py-2" rows="3" placeholder="请描述模板用途" required></textarea>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">策略配置</label>
                    <div class="space-y-2">
                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="requireApproval" id="requireApproval" class="rounded text-blue-600 focus:ring-blue-500">
                            <label for="requireApproval" class="text-sm text-gray-700">需要审批</label>
                        </div>
                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="autoRotate" id="autoRotate" class="rounded text-blue-600 focus:ring-blue-500">
                            <label for="autoRotate" class="text-sm text-gray-700">自动轮换</label>
                        </div>
                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="enableBackup" id="enableBackup" class="rounded text-blue-600 focus:ring-blue-500">
                            <label for="enableBackup" class="text-sm text-gray-700">启用备份</label>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end gap-2">
                    <button type="button" onclick="closeAddTemplateModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50">取消</button>
                    <button type="submit" class="btn btn-primary px-4 py-2 rounded-lg">创建模板</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑模板模态框 -->
    <div id="editTemplateModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="card p-6 w-full max-w-lg">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">编辑密钥模板</h3>
                <button onclick="closeEditTemplateModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="editTemplateForm" class="space-y-4">
                <input type="hidden" name="id">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">模板名称</label>
                    <input type="text" name="name" class="input-field w-full px-4 py-2" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">算法</label>
                    <select name="algorithm" class="input-field w-full px-4 py-2" required>
                        <option value="SM2">SM2</option>
                        <option value="RSA">RSA</option>
                        <option value="SM4">SM4</option>
                        <option value="AES">AES</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">默认密钥长度</label>
                    <input type="number" name="defaultLength" class="input-field w-full px-4 py-2" min="128" max="4096" required>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">用途</label>
                    <textarea name="purpose" class="input-field w-full px-4 py-2" rows="3" required></textarea>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                    <select name="status" class="input-field w-full px-4 py-2" required>
                        <option value="active">启用</option>
                        <option value="inactive">禁用</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">策略配置</label>
                    <div class="space-y-2">
                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="requireApproval" class="rounded text-blue-600 focus:ring-blue-500">
                            <label class="text-sm text-gray-700">需要审批</label>
                        </div>
                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="autoRotate" class="rounded text-blue-600 focus:ring-blue-500">
                            <label class="text-sm text-gray-700">自动轮换</label>
                        </div>
                        <div class="flex items-center gap-2">
                            <input type="checkbox" name="enableBackup" class="rounded text-blue-600 focus:ring-blue-500">
                            <label class="text-sm text-gray-700">启用备份</label>
                        </div>
                    </div>
                </div>
                <div class="flex justify-end gap-2">
                    <button type="button" onclick="closeEditTemplateModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50">取消</button>
                    <button type="submit" class="btn btn-primary px-4 py-2 rounded-lg">保存修改</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div id="deleteTemplateModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="card p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">确认删除</h3>
                <button onclick="closeDeleteTemplateModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="mb-4">
                <p>您确定要删除模板 <span id="deleteTemplateName" class="font-medium"></span> 吗？</p>
                <p class="text-sm text-gray-500 mt-2">此操作无法撤销，相关密钥可能会受到影响。</p>
            </div>
            <div class="flex justify-end gap-2">
                <button onclick="closeDeleteTemplateModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50">取消</button>
                <button onclick="confirmDeleteTemplate()" class="btn btn-danger px-4 py-2 rounded-lg">删除</button>
            </div>
        </div>
    </div>

    <!-- 策略配置模态框 -->
    <div id="policyModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="card p-6 w-full max-w-md">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-semibold">策略配置</h3>
                <button onclick="closePolicyModal()" class="text-gray-500 hover:text-gray-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div id="policyContent" class="space-y-3">
                <!-- 策略内容将动态生成 -->
            </div>
            <div class="flex justify-end mt-4">
                <button onclick="closePolicyModal()" class="px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50">关闭</button>
            </div>
        </div>
    </div>

    <script src="../common/common.js"></script>
    <script>
        // 初始化数据
        function initData() {
            showLoading(document.body);
            // 初始化模板数据（如果不存在）
            if (!localStorage.getItem('demo_templates')) {
                const initialTemplates = [
                    { id: 'TMP-001', name: '标准SM2模板', algorithm: 'SM2', defaultLength: 256, purpose: '数字签名和加密', status: 'active', policies: { requireApproval: true, autoRotate: true, enableBackup: true } },
                    { id: 'TMP-002', name: '通用AES模板', algorithm: 'AES', defaultLength: 128, purpose: '数据加密', status: 'active', policies: { requireApproval: false, autoRotate: false, enableBackup: true } },
                    { id: 'TMP-003', name: '高强度RSA模板', algorithm: 'RSA', defaultLength: 2048, purpose: '身份认证', status: 'active', policies: { requireApproval: true, autoRotate: true, enableBackup: true } },
                    { id: 'TMP-004', name: '快速SM4模板', algorithm: 'SM4', defaultLength: 128, purpose: '快速数据加密', status: 'active', policies: { requireApproval: false, autoRotate: false, enableBackup: false } },
                    { id: 'TMP-005', name: '超强度RSA模板', algorithm: 'RSA', defaultLength: 4096, purpose: '高级身份认证', status: 'active', policies: { requireApproval: true, autoRotate: true, enableBackup: true } }
                ];
                localStorage.setItem('demo_templates', JSON.stringify(initialTemplates));
            }
            setTimeout(() => {
                hideLoading(document.body, '');
            }, 500);
        }

        // 加载模板表格
        function loadTemplates() {
            showLoading(document.body);
            
            // 从localStorage获取模板数据
            const templates = JSON.parse(localStorage.getItem('demo_templates') || '[]');
            const tbody = document.getElementById('templatesTableBody');
            
            // 检查表格主体元素是否存在
            if (!tbody) {
                hideLoading(document.body, '');
                showToast('模板表格主体元素未找到', 'error');
                return;
            }
            
            tbody.innerHTML = '';
      
            if (templates.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="7" class="py-8 text-center text-gray-500 animate-fadeInUp">
                            <i class="fas fa-folder-open text-4xl mb-2"></i>
                            <p>暂无模板数据</p>
                            <button onclick="openAddTemplateModal()" class="mt-2 btn btn-primary px-4 py-1 rounded-lg">
                                <i class="fas fa-plus"></i> 立即创建
                            </button>
                        </td>
                    </tr>
                `;
                hideLoading(document.body, '');
                return;
            }

            templates.forEach((template, index) => {
                const row = document.createElement('tr');
                row.className = 'table-row border-b border-gray-100 animate-fadeInUp';
                row.style.animationDelay = `${index * 0.05}s`;
                row.innerHTML = `
                    <td class="py-3 px-4">${template.id}</td>
                    <td class="py-3 px-4">${template.name}</td>
                    <td class="py-3 px-4">${template.algorithm}</td>
                    <td class="py-3 px-4">${template.defaultLength}</td>
                    <td class="py-3 px-4">${template.purpose}</td>
                    <td class="py-3 px-4">
                        <span class="status-badge ${template.status === 'active' ? 'status-active' : 'status-inactive'}">
                            ${template.status === 'active' ? '启用' : '禁用'}
                        </span>
                    </td>
                    <td class="py-3 px-4">
                        <div class="flex gap-2">
                            <button onclick="editTemplate('${template.id}')" class="text-blue-600 hover:text-blue-800 transition-colors duration-200" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                            <button onclick="deleteTemplate('${template.id}')" class="text-red-600 hover:text-red-800 transition-colors duration-200" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                            <button onclick="configurePolicy('${template.id}')" class="text-purple-600 hover:text-purple-800 transition-colors duration-200" title="策略配置">
                                <i class="fas fa-cog"></i>
                            </button>
                        </div>
                    </td>
                `;
                tbody.appendChild(row);
            });
            hideLoading(document.body, '');
        }

        // 搜索和筛选功能
        function setupSearchAndFilter() {
            console.log('开始设置搜索和筛选功能');
            
            // 直接获取搜索和过滤元素
            const searchInput = document.getElementById('searchInput');
            const templateTypeFilter = document.getElementById('templateTypeFilter');
            const tbody = document.getElementById('templatesTableBody');
            
            // 检查搜索和过滤元素是否存在
            if (!searchInput || !templateTypeFilter) {
                console.error('搜索和过滤元素均未找到');
                showToast('搜索功能初始化失败', 'error');
                return;
            }
            
            // 再次检查表格主体元素
            if (!tbody) {
                console.error('模板表格主体元素未找到');
                return;
            }
            
            function filterTemplates() {
                showLoading(document.body);
                // 安全获取值，避免访问不存在的属性
                const searchTerm = searchInput ? searchInput.value.toLowerCase() : '';
                const algorithm = templateTypeFilter ? templateTypeFilter.value : '';
                const templates = JSON.parse(localStorage.getItem('demo_templates')) || [];
                const tbody = document.getElementById('templatesTableBody');
                
                // 检查tbody元素是否存在
                if (!tbody) {
                    console.error('模板表格主体元素未找到');
                    hideLoading(document.body, '');
                    return;
                }
                
                tbody.innerHTML = '';

                const filteredTemplates = templates.filter(template => {
                    const matchesSearch = template.name.toLowerCase().includes(searchTerm) || template.id.toLowerCase().includes(searchTerm);
                    const matchesAlgorithm = algorithm ? template.algorithm === algorithm : true;
                    return matchesSearch && matchesAlgorithm;
                });

                if (filteredTemplates.length === 0) {
                    tbody.innerHTML = `
                        <tr>
                            <td colspan="7" class="py-8 text-center text-gray-500 animate-fadeInUp">
                                <i class="fas fa-search text-4xl mb-2"></i>
                                <p>没有找到匹配的模板</p>
                                <p class="text-sm mt-1">请尝试调整搜索条件</p>
                            </td>
                        </tr>
                    `;
                    hideLoading(document.body, '');
                    return;
                }

                filteredTemplates.forEach((template, index) => {
                    const row = document.createElement('tr');
                    row.className = 'table-row border-b border-gray-100 animate-fadeInUp';
                    row.style.animationDelay = `${index * 0.05}s`;
                    row.innerHTML = `
                        <td class="py-3 px-4">${template.id}</td>
                        <td class="py-3 px-4">${template.name}</td>
                        <td class="py-3 px-4">${template.algorithm}</td>
                        <td class="py-3 px-4">${template.defaultLength}</td>
                        <td class="py-3 px-4">${template.purpose}</td>
                        <td class="py-3 px-4">
                            <span class="status-badge ${template.status === 'active' ? 'status-active' : 'status-inactive'}">
                                ${template.status === 'active' ? '启用' : '禁用'}
                            </span>
                          </td>
                        <td class="py-3 px-4">
                            <div class="flex gap-2">
                                <button onclick="editTemplate('${template.id}')" class="text-blue-600 hover:text-blue-800 transition-colors duration-200" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button onclick="deleteTemplate('${template.id}')" class="text-red-600 hover:text-red-800 transition-colors duration-200" title="删除">
                                    <i class="fas fa-trash"></i>
                                </button>
                                <button onclick="configurePolicy('${template.id}')" class="text-purple-600 hover:text-purple-800 transition-colors duration-200" title="策略配置">
                                    <i class="fas fa-cog"></i>
                                </button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(row);
                });
                hideLoading(document.body, '');
            }

            // 检查元素是否存在再添加事件监听器
            if (searchInput) {
                searchInput.addEventListener('input', filterTemplates);
            }
            if (templateTypeFilter) {
                templateTypeFilter.addEventListener('change', filterTemplates);
            }
        }

        // 新增模板
        function openAddTemplateModal() {
            openModal('addTemplateModal');
        }

        function closeAddTemplateModal() {
            closeModal('addTemplateModal');
            document.getElementById('addTemplateForm').reset();
        }

        // 表单提交事件
        document.getElementById('addTemplateForm').addEventListener('submit', (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            
            // 表单验证
            const name = formData.get('name').trim();
            const algorithm = formData.get('algorithm');
            const defaultLength = parseInt(formData.get('defaultLength'));
            const purpose = formData.get('purpose').trim();
            
            if (!name) {
                showToast('模板名称不能为空', 'error');
                return;
            }
            
            if (!algorithm) {
                showToast('请选择算法', 'error');
                return;
            }
            
            if (isNaN(defaultLength) || defaultLength < 128 || defaultLength > 4096) {
                showToast('密钥长度必须在128-4096之间', 'error');
                return;
            }
            
            if (!purpose) {
                showToast('模板用途不能为空', 'error');
                return;
            }

            const submitBtn = e.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            showLoading(submitBtn);
            
            const template = {
                id: `TMP-${generateUniqueId(3)}`,
                name: name,
                algorithm: algorithm,
                defaultLength: defaultLength,
                purpose: purpose,
                status: 'active',
                policies: {
                    requireApproval: formData.get('requireApproval') === 'on',
                    autoRotate: formData.get('autoRotate') === 'on',
                    enableBackup: formData.get('enableBackup') === 'on'
                }
            };

            const templates = JSON.parse(localStorage.getItem('demo_templates')) || [];
            templates.push(template);
            localStorage.setItem('demo_templates', JSON.stringify(templates));
            
            setTimeout(() => {
                hideLoading(submitBtn, originalText);
                closeAddTemplateModal();
                loadTemplates();
                showToast('模板创建成功！', 'success');
            }, 1500);
        });

        // 编辑模板
        let currentEditTemplateId = null;
        
        function editTemplate(templateId) {
            showLoading(document.body);
            const templates = JSON.parse(localStorage.getItem('demo_templates')) || [];
            const template = templates.find(t => t.id === templateId);
            
            if (template) {
                document.getElementById('editTemplateForm').name.value = template.name;
                document.getElementById('editTemplateForm').algorithm.value = template.algorithm;
                document.getElementById('editTemplateForm').defaultLength.value = template.defaultLength;
                document.getElementById('editTemplateForm').purpose.value = template.purpose;
                document.getElementById('editTemplateForm').status.value = template.status;
                document.getElementById('editTemplateForm').requireApproval.checked = template.policies.requireApproval;
                document.getElementById('editTemplateForm').autoRotate.checked = template.policies.autoRotate;
                document.getElementById('editTemplateForm').enableBackup.checked = template.policies.enableBackup;
                document.getElementById('editTemplateForm').id.value = template.id;
                
                currentEditTemplateId = templateId;
                hideLoading(document.body, '');
                openModal('editTemplateModal');
            } else {
                hideLoading(document.body, '');
                showToast('未找到指定模板', 'error');
            }
        }
        
        function closeEditTemplateModal() {
            closeModal('editTemplateModal');
            document.getElementById('editTemplateForm').reset();
            currentEditTemplateId = null;
        }
        
        // 编辑模板表单提交
        document.getElementById('editTemplateForm').addEventListener('submit', (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const templateId = formData.get('id');
            
            // 表单验证
            const name = formData.get('name').trim();
            const algorithm = formData.get('algorithm');
            const defaultLength = parseInt(formData.get('defaultLength'));
            const purpose = formData.get('purpose').trim();
            
            if (!name) {
                showToast('模板名称不能为空', 'error');
                return;
            }
            
            if (!algorithm) {
                showToast('请选择算法', 'error');
                return;
            }
            
            if (isNaN(defaultLength) || defaultLength < 128 || defaultLength > 4096) {
                showToast('密钥长度必须在128-4096之间', 'error');
                return;
            }
            
            if (!purpose) {
                showToast('模板用途不能为空', 'error');
                return;
            }

            const submitBtn = e.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            showLoading(submitBtn);
            
            const templates = JSON.parse(localStorage.getItem('demo_templates')) || [];
            const templateIndex = templates.findIndex(t => t.id === templateId);
            
            if (templateIndex !== -1) {
                templates[templateIndex] = {
                    ...templates[templateIndex],
                    name: name,
                    algorithm: algorithm,
                    defaultLength: defaultLength,
                    purpose: purpose,
                    status: formData.get('status'),
                    policies: {
                        requireApproval: formData.get('requireApproval') === 'on',
                        autoRotate: formData.get('autoRotate') === 'on',
                        enableBackup: formData.get('enableBackup') === 'on'
                    }
                };
                
                localStorage.setItem('demo_templates', JSON.stringify(templates));
                
                setTimeout(() => {
                    hideLoading(submitBtn, originalText);
                    closeEditTemplateModal();
                    loadTemplates();
                    showToast('模板修改成功！', 'success');
                }, 500);
            } else {
                hideLoading(submitBtn, originalText);
                showToast('未找到指定模板', 'error');
            }
        });

        // 删除模板
        let currentDeleteTemplateId = null;
        
        function deleteTemplate(templateId) {
            showLoading();
            const templates = JSON.parse(localStorage.getItem('demo_templates')) || [];
            const template = templates.find(t => t.id === templateId);
            
            if (template) {
                document.getElementById('deleteTemplateName').textContent = template.name;
                currentDeleteTemplateId = templateId;
                hideLoading();
                document.getElementById('deleteTemplateModal').classList.remove('hidden');
            } else {
                hideLoading();
                showToast('未找到指定模板', 'error');
            }
        }
        
        function closeDeleteTemplateModal() {
            document.getElementById('deleteTemplateModal').classList.add('hidden');
            currentDeleteTemplateId = null;
        }
        
        function confirmDeleteTemplate() {
            if (currentDeleteTemplateId) {
                showLoading();
                const templates = JSON.parse(localStorage.getItem('demo_templates')) || [];
                const updatedTemplates = templates.filter(template => template.id !== currentDeleteTemplateId);
                localStorage.setItem('demo_templates', JSON.stringify(updatedTemplates));
                
                // 检查是否有密钥使用了该模板
                const keys = JSON.parse(localStorage.getItem('demo_keys')) || [];
                const keysUsingTemplate = keys.filter(key => key.templateId === currentDeleteTemplateId);
                
                setTimeout(() => {
                    hideLoading();
                    closeDeleteTemplateModal();
                    loadTemplates();
                    
                    if (keysUsingTemplate.length > 0) {
                        showToast(`模板删除成功！注意：有${keysUsingTemplate.length}个密钥仍引用此模板`, 'warning');
                    } else {
                        showToast('模板删除成功！', 'success');
                    }
                }, 500);
            }
        }

        // 配置策略
        function configurePolicy(templateId) {
            showLoading();
            const templates = JSON.parse(localStorage.getItem('demo_templates')) || [];
            const template = templates.find(t => t.id === templateId);
            
            if (template) {
                const policyContent = document.getElementById('policyContent');
                policyContent.innerHTML = `
                    <div class="border-b pb-2">
                        <h4 class="font-medium">${template.name} (${template.id})</h4>
                        <p class="text-sm text-gray-500">算法: ${template.algorithm}, 长度: ${template.defaultLength}</p>
                    </div>
                    <div>
                        <p class="text-sm font-medium">策略详情:</p>
                        <div class="mt-1 grid grid-cols-2 gap-2">
                            <div class="flex items-center gap-2">
                                <i class="fas ${template.policies.requireApproval ? 'fa-check-circle text-green-500' : 'fa-times-circle text-red-500'}"></i>
                                <span class="text-sm">需要审批</span>
                            </div>
                            <div class="flex items-center gap-2">
                                <i class="fas ${template.policies.autoRotate ? 'fa-check-circle text-green-500' : 'fa-times-circle text-red-500'}"></i>
                                <span class="text-sm">自动轮换</span>
                            </div>
                            <div class="flex items-center gap-2">
                                <i class="fas ${template.policies.enableBackup ? 'fa-check-circle text-green-500' : 'fa-times-circle text-red-500'}"></i>
                                <span class="text-sm">启用备份</span>
                            </div>
                        </div>
                    </div>
                    <div class="bg-blue-50 p-3 rounded-lg">
                        <p class="text-sm text-blue-700">
                            <i class="fas fa-info-circle mr-1"></i>
                            策略说明：
                        </p>
                        <ul class="text-xs text-blue-600 mt-1 list-disc list-inside">
                            <li>需要审批：使用此模板创建密钥需要管理员审批</li>
                            <li>自动轮换：密钥将按照系统设置自动轮换</li>
                            <li>启用备份：密钥将自动备份到安全存储</li>
                        </ul>
                    </div>
                `;
                hideLoading();
                document.getElementById('policyModal').classList.remove('hidden');
            } else {
                hideLoading();
                showToast('未找到指定模板', 'error');
            }
        }
        
        function closePolicyModal() {
            document.getElementById('policyModal').classList.add('hidden');
        }

        // 模态框关闭事件（点击外部或ESC键）
        document.addEventListener('click', (e) => {
            const modals = [
                document.getElementById('addTemplateModal'),
                document.getElementById('editTemplateModal'),
                document.getElementById('deleteTemplateModal'),
                document.getElementById('policyModal')
            ];
            
            modals.forEach(modal => {
                if (modal && !modal.classList.contains('hidden') && e.target === modal) {
                    if (modal.id === 'addTemplateModal') closeAddTemplateModal();
                    if (modal.id === 'editTemplateModal') closeEditTemplateModal();
                    if (modal.id === 'deleteTemplateModal') closeDeleteTemplateModal();
                    if (modal.id === 'policyModal') closePolicyModal();
                }
            });
        });
        
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                closeAddTemplateModal();
                closeEditTemplateModal();
                closeDeleteTemplateModal();
                closePolicyModal();
            }
        });

        // 页面加载时初始化
        function initApp() {
            try {
                console.log('进入initApp函数');
                // 首先初始化数据
                initData();
                
                // 直接加载模板和设置搜索筛选功能，因为已经确保元素存在
                console.log('调用loadTemplates');
                loadTemplates();
                console.log('调用setupSearchAndFilter');
                setupSearchAndFilter();
            } catch (e) {
                console.error('初始化功能时出错:', e);
                hideLoading(document.body, '');
                showToast('初始化失败，请刷新页面重试', 'error');
            }
        }
        

        
        // 使用更可靠的方法来确保DOM完全加载
        function ensureDOMLoaded(callback) {
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', callback);
            } else {
                callback();
            }
        }
        
        // 临时添加showLoading和hideLoading函数，解决common.js未加载的问题
        function showLoading(element) {
            if (!element) return;
            console.log('显示加载状态');
        }
        
        function hideLoading(element, originalText) {
            if (!element) return;
            console.log('隐藏加载状态');
        }
        
        // 页面加载完成后初始化
        ensureDOMLoaded(function() {
            // 延迟执行，确保所有异步DOM操作完成
            setTimeout(function() {
                // 使用setInterval检查，确保元素确实存在
                let checkCount = 0;
                const maxChecks = 50; // 最多检查50次，每次100ms，共5秒
                
                const checkInterval = setInterval(function() {
                    checkCount++;
                    const tbody = document.getElementById('templatesTableBody');
                    
                    if (tbody) {
                        clearInterval(checkInterval);
                        initApp();
                    } else {
                        if (checkCount >= maxChecks) {
                            clearInterval(checkInterval);
                            showToast('模板表格主体元素未找到', 'error');
                        }
                    }
                }, 100);
            }, 500); // 额外延迟500ms
        });
    </script>
</body>
</html>